package com.example.demo.controller;

import com.example.demo.model.LoginUser;
import com.example.demo.model.TokenUser;
import com.example.demo.service.HomeService;
import com.example.demo.tools.Constant;
import com.example.demo.tools.RedisUtil;
import com.example.demo.tools.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WJ
 * Date: 2023-02-18
 * Time: 11:05
 */
@RestController
@RequestMapping("/home")
public class HomeController {

    @Autowired
    private HomeService homeService;

    @Autowired
    private RedisUtil redisUtil;

//    登录逻辑
    @RequestMapping("/login")
    public Object login( @RequestParam String phone,
                         @RequestParam String password){

        return homeService.login(phone,password);
    }

//    注销逻辑
    @RequestMapping("/exitlogin")
    public Object logout(){
        // 通过 SecurityContextHolder 获取到当前请求的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TokenUser loginUser = (TokenUser) authentication.getPrincipal();
        // 从 redis 中进行清除
        redisUtil.deleteObject("login:"+loginUser.getUser().getId());
        return true;
    }

//    获取侧边栏的菜单列表
    @RequestMapping("/getmenulist")
    public Object getMenulist(){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TokenUser principal = (TokenUser) authentication.getPrincipal();
        LoginUser user = principal.getUser();
        if(user != null){
            if("超级管理员".equals(user.getStatus())){
                // 返回系统管理员的菜单
                return Constant.getAdminMenuList();
            }else if("员工".equals(user.getStatus())){
                // 返回员工的菜单
                return Constant.getEmployeeMenuList();
            }
        }
        return "菜单栏获取失败";
    }

//    柱状图的数据
    @RequestMapping("/getoption")
    public Object getOption(){
        return homeService.getOption();
    }

//    为首页提供系统公告数据（需要截取context）
    @RequestMapping("/getnotice")
    public Object getNoticeListForFirstHome(@RequestParam(value = "isnotice") Boolean isNotice){
        if(isNotice == null){
            return "获取公告数据失败!";
        }else{
            return homeService.getNoticeList(isNotice);
        }
    }
}
